<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { ElTable, ElTableColumn, ElPagination, ElMessageBox } from 'element-plus';
import { login, getPageAuth, delAuth, addAuth, updateAuth } from '@/api'
import { setAccessToken } from '@/utils'
import { success,error } from '@/utils'
import '@/assets/css/index.css'

// 当前数据页数
const currentPage = ref(1);

// const statePage = ref(1);
// 一页数据的大小
const pageSize = ref(10);
//总数据条数
const total = ref(0);
// 表格数据
const tableData = ref([]);

// 权限是否隐藏，默认状态为false
const state = ref(false);
// 删除按钮的状态
const delButtonState = ref(true);
// 添加权限的表单是否显示
const add_auth_state = ref(false);

//加载状态
const loading = ref(false)
// 修改权限的表单是否显示
const modify_auth_state = ref(false);

// 修改权限的对照对象
const oneAuth = ref({});

//表单校验
interface TableForm {
  id: number;
  pid: number;
  countSub: number;
  sort?: number;
  type?: string;
  name: string;
  path: string;
  redirect?: string;
  component?: string;
  metaIcon?: string;
  permission?: string;
  href: string;
  module: string;
  uri: string;
  isHidden: boolean;
  createBy: string;
}

// 添加表单变量
const add_auth_form = reactive<TableForm>({
  id: -1 as unknown as number,
  pid: 0,
  countSub: 0,
  sort: undefined,
  type: '',
  name: '',
  path: '',
  redirect: '',
  component: '',
  metaIcon: '',
  permission: '',
  href: '',
  module: '',
  uri: '',
  isHidden: false,
  createBy: ''
})
// 修改权限的表单变量
const modification_auth_form = reactive<TableForm>({
  id: -1 as unknown as number,
  pid: 0,
  countSub: 0,
  sort: undefined,
  type: '',
  name: '',
  path: '',
  redirect: '',
  component: '',
  metaIcon: '',
  permission: undefined,
  href: '',
  module: '',
  uri: '',
  isHidden: false,
  createBy: ''
})

// 表单校验
const rules = {
  id: [
    { required: true, message: '请输入权限id', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
    { pattern: /^([0-9]+)*$/, message: '格式应该为数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
  ],
  new_name: [
    { required: false, message: '请输入权限名称', trigger: 'blur' },
    { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
  ],
  new_path: [
    { required: false, message: '请输入权限路径', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入权限路径', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  component: [
    { required: false, message: '请输入组件路径', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  metaIcon: [
    { required: false, message: '请输入图标的路径', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  permission: [
    { required: true, message: '请确认输入数据正确', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
    { pattern: /^([a-zA-Z0-9]+):([a-zA-Z0-9]+)$/, message: '格式应该为string:string', trigger: 'blur' }
  ],
  new_permission: [
    { required: false, message: '请确认输入数据正确', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
    { pattern: /^([a-zA-Z0-9]+):([a-zA-Z0-9]+)$/, message: '格式应该为string:string', trigger: 'blur' }
  ],
  href: [
    { required: false, message: '请输入跳转链接', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  module: [
    { required: true, message: '请输入模块名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  new_module: [
    { required: false, message: '请输入模块名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  uri: [
    { required: true, message: '请输入接口地址', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  new_uri: [
    { required: false, message: '请输入接口地址', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  isHidden: [
    { required: true, message: '请选择是否隐藏', trigger: 'blur' },
  ],
  new_isHidden: [
    { required: false, message: '请选择是否隐藏', trigger: 'blur' },
  ],
  createBy: [
    { required: true, message: '请输入创建人', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  new_createBy: [
    { required: false, message: '请输入创建人', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: false, message: '请选择权限类型', trigger: 'blur' },
    { min: 1, max: 1, message: '根据类型选择', trigger: 'blur' }
  ],
  redirect: [
    { required: false, message: '请输入跳转链接', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: false, message: '请输入排序', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  pid: [
    { required: true, message: '请选择父级权限', trigger: 'blur' },
  ],
  new_pid: [
    { required: false, message: '请选择父级权限', trigger: 'blur' },
  ],
  countSub: [
    { required: true, message: '请输入子权限数量', trigger: 'blur' },
    { min: 1, max: 1, message: '填写为一个数字', trigger: 'blur' }
  ],
  new_countSub: [
    { required: false, message: '请输入子权限数量', trigger: 'blur' }
  ]
}

//存储删除的数据的id
let delList: Array<number> = [];

// 上部查询数据的条件
const authform = reactive({
  name: '',
  sort: '',
  ctime: ''
});


// 初始化数据
onMounted(() => {
  fetchData()
});


//修改一下时间，去除后面的hour、minute、second
const formatDates = () => {
  tableData.value.forEach((item: any) => {
    item.createTime = item.createTime.substring(0, 10);
    item.updateTime = item.updateTime.substring(0, 10);
  })
}

//从后端获取数据
const fetchData = () => {
  getPageAuth(
    {
      current: currentPage.value,
      size: pageSize.value,
      sort: authform.sort,
      name: authform.name,
      isHidden: state.value,
      createTime: authform.ctime,
    }).then(response => {
      if (response.data) {
        const data = response.data;
        total.value = data.total;
        tableData.value = data.records;
        formatDates()
      } else {
        error("获取数据失败")
      }

    });
};


// 根据页数查询（切换页数）
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  // 根据新的页码重新获取数据
  fetchData();
};

//检测排序是否改变，改变则重新获取数据
const handleSortChange = () => {
  fetchData();
};


// 选择数据改变
const handleSelectionChange = (selection: any) => {
  delList = [];
  delList = selection.map((item: any) => item.id);
  if (delList.length <= 0) {
    delButtonState.value = true;
  } else {
    delButtonState.value = false;
  }
}

// 数据条件查询
const queryByName = async () => {
  fetchData()
}


const addAction = () => {
  loadingMethod()
  addAuth(add_auth_form).then(response => {
    if (response.data) {
      clearAddForm()
      success("添加成功")
    } else {
      error("添加失败")
    }

  })
}
// 修改数据
const modifyAction = async () => {
  loadingMethod()
  modification_auth_form.id = oneAuth.value.id
  const res = await updateAuth(modification_auth_form)
  if (res.data===2000) {
    success("更新成功")
    clearModifyForm()
  } else {
    error("更新失败")
  }
}

// 删除数据
const delAction = () => {
  console.log({ delList })
  delAuth(delList).then(response => {
    if (response.data) {
      fetchData()
      success("删除成功")
    } else {
      error("删除失败")
    }

  })
}

//弹出添加表单
const popAddForm = () => {
  add_auth_state.value = true;
}

//弹出修改表单
const popModifyForm = (row: any) => {
  modify_auth_state.value = true;
  oneAuth.value = row
}

// 返回刚才的表格，但是是从后端重新获取的
const returnInit = () => {
  state.value = false;
  authform.name = '';
  authform.sort = '';
  authform.ctime = '';
  fetchData()
}



// 充重置对象的值
const clearAddForm = () => {
  add_auth_form.pid = 0,
    add_auth_form.countSub = 0,
    add_auth_form.sort = undefined,
    add_auth_form.type = '',
    add_auth_form.name = '',
    add_auth_form.path = '',
    add_auth_form.redirect = '',
    add_auth_form.component = '',
    add_auth_form.metaIcon = '',
    add_auth_form.permission = '',
    add_auth_form.href = '',
    add_auth_form.module = '',
    add_auth_form.uri = '',
    add_auth_form.isHidden = false,
    add_auth_form.createBy = ''
}

const clearModifyForm = () => {
  modification_auth_form.id = -1,
  modification_auth_form.pid = 0,
  modification_auth_form.countSub= 0,
  modification_auth_form.sort= undefined,
  modification_auth_form.type= '',
  modification_auth_form.name= '',
  modification_auth_form.path= '',
  modification_auth_form.redirect= '',
  modification_auth_form.component= '',
  modification_auth_form.metaIcon= '',
  modification_auth_form.permission= undefined,
  modification_auth_form.href= '',
  modification_auth_form.module= '',
  modification_auth_form.uri= '',
  modification_auth_form.isHidden= false,
  modification_auth_form.createBy= ''
}

const loadingMethod = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 400)
}

const handleClose = (done: any) => {
  if (loading.value) {
    return
  }
  ElMessageBox.confirm('你要提交表单吗？')
    .then(() => {
      loading.value = true
      const timer = setTimeout(() => {
        done()
        // 动画关闭需要一定的时间
        setTimeout(() => {
          loading.value = false
        }, 400)
      }, 2000)
    })
    .catch(() => {
      console.log("出现故障")
    })
}

const cancelForm = () => {
  add_auth_state.value = false;
  modify_auth_state.value = false;
  loading.value = false
  clearModifyForm()
}
</script>


<template>
  <div class="header"
    style="height: 50px;min-width: 1170px;width: 100%;position: absolute;left: 0;top:0;background-color: aqua;">
  </div>

  <div class="aside"
    style="height:calc(100% - 50px);width: 220px; position: absolute; left: 0; top:50px;background-color: aqua;">
  </div>


  <div class="auth" style="position: absolute;left: 220px;top:70px;">
    <!--      遮罩层-->

    <el-form :block="true" :model="authform"
             class="authForm"
             status-icon>
      <el-form-item label="权限名称" class="auth_item" label-position="top" size="large">
        <el-input v-model="authform.name" placeholder="权限名称" />
      </el-form-item>


      <el-form-item label="状态" prop="state" class="auth_item" size="large">
        <el-select v-model="state" placeholder="状态" clearable>
          <el-option label="正常" value=false />
          <el-option label="隐藏" value=true />
        </el-select>
      </el-form-item>

      <el-form-item label="创建日期" prop="ctime" class="auth_item" size="large">
        <el-date-picker v-model="authform.ctime" type="date" placeholder="选择日期" format="YYYY/MM/DD"
          value-format="YYYY-MM-DD" clearable />
      </el-form-item>

      <el-form-item label="修改时间排序" prop="ctime" class="auth_item" size="large">
        <el-select v-model="authform.sort" placeholder="不参与查询" @change="handleSortChange" clearable>
          <el-option label="升序" value="asc" />
          <el-option label="降序" value="desc" />
        </el-select>
      </el-form-item>
      <el-button type="primary" @click="queryByName" size="large">查询</el-button>
      <el-form-item class="auth_item" size="large">
        <el-button type="primary" size="large" plain @click="returnInit">返回</el-button>
        <el-button type="primary" size="large" plain :disabled="delButtonState" @click="delAction">删除</el-button>
        <el-button type="primary" size="large" plain @click="popAddForm">添加</el-button>
      </el-form-item>
    </el-form>


    <el-table :data="tableData" border class="authTable" @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="id" label="ID" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="pid" label="上级" />
      <el-table-column prop="countSub" label="子菜单数" />
      <el-table-column prop="path" label="路径" />
      <el-table-column prop="uri" label="接口" />
      <el-table-column prop="isHidden" label="是否隐藏" />
      <el-table-column prop="isDeleted" label="存在" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="updateTime" label="修改日期" />
      <el-table-column label="操作" placeholder="操作">
        <template #default="{ row }">
          <el-button type="text" @click="popModifyForm(row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
      layout="prev, pager, next, jumper" :total="total" style="float: right;margin-right: 15px;"></el-pagination>

    <!--      权限添加表单-->
    <el-drawer v-model="add_auth_state" :with-header="false" :before-close="handleClose" direction="ltr"
      class="addtion-drawer" style="min-width: 300px;">
      <h3 style="text-align: center;">添加权限</h3><br />
      <el-form :inline="true" :model="add_auth_form" :rules="rules" class="addAuthForm" label-width="auto"
        label-position="left" size="large" status-icon>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="add_auth_form.name" placeholder="权限名称" prop="name" />
        </el-form-item>
        <el-form-item label="权限上级" prop="pid">
          <el-input v-model="add_auth_form.pid" placeholder="上级权限" prop="pid" />
        </el-form-item>
        <el-form-item label="路由路径" prop="path">
          <el-input v-model="add_auth_form.path" placeholder="路径" prop="path" />
        </el-form-item>
        <el-form-item label="后端接口" prop="uri">
          <el-input v-model="add_auth_form.uri" placeholder="接口" prop="uri" />
        </el-form-item>
        <el-form-item label="是否隐藏" prop="isHidden">
          <el-switch v-model="add_auth_form.isHidden" active-color="#13ce66" inactive-color="#ff4949" />
        </el-form-item>
        <el-form-item label="子菜单数" prop="countSub">
          <el-input v-model="add_auth_form.countSub" placeholder="子菜单数" />
        </el-form-item>
        <el-form-item label="组件名称" prop="component">
          <el-input v-model="add_auth_form.component" placeholder="组件名称" />
        </el-form-item>
        <el-form-item label="重定向" prop="redirect">
          <el-input v-model="add_auth_form.redirect" placeholder="重定向路径" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="add_auth_form.sort" placeholder="排序" />
        </el-form-item>
        <el-form-item label="超链接" prop="href">
          <el-input v-model="add_auth_form.href" placeholder="超链接" />
        </el-form-item>
        <el-form-item label="图标路径" prop="metaIcon">
          <el-input v-model="add_auth_form.metaIcon" placeholder="图标" />
        </el-form-item>
        <el-form-item label="模块名称" prop="module">
          <el-input v-model="add_auth_form.module" placeholder="模块名称" />
        </el-form-item>
        <el-form-item label="类型名称" prop="type">
          <el-input v-model="add_auth_form.type" placeholder="类型名称" />
        </el-form-item>
        <el-form-item label="允许" prop="permission">
          <el-input v-model="add_auth_form.permission" placeholder="请确认数据的格式正确性" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addAction" :loading="loading" size="large">提交</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="cancelForm" size="large">返回</el-button>
        </el-form-item>

      </el-form>
    </el-drawer>


    <!--      权限修改表单-->
    <el-drawer v-model="modify_auth_state" :with-header="false" :before-close="handleClose" direction="ltr"
      class="modification-drawer" style="min-width: 300px;">
      <h3 style="text-align: center;">修改（{{ oneAuth.name }}）</h3><br>
      <el-form :inline="true" :model="modification_auth_form" :rules="rules" class="modifyAuthForm" label-width="auto"
               label-position="left" size="large" status-icon>
        <el-form-item label="权限ID" prop="id">
          <el-input v-model="oneAuth.id" placeholder="权限ID" prop="id" disabled />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="oneAuth.name" placeholder="权限名称" prop="name" disabled />
        </el-form-item>
        <el-form-item label="新权限名称" prop="new_name">
          <el-input v-model="modification_auth_form.name" placeholder="" prop="name" />
        </el-form-item>
        <el-form-item label="权限上级" prop="pid">
          <el-input v-model="oneAuth.pid" placeholder="上级权限" prop="pid" disabled />
        </el-form-item>
        <el-form-item label="新权限上级" prop="new_pid">
          <el-input v-model="modification_auth_form.pid" placeholder="上级权限" prop="pid" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="path">
          <el-input v-model="oneAuth.path" placeholder="路径" prop="path" disabled />
        </el-form-item>
        <el-form-item label="新菜单路径" prop="new_path">
          <el-input v-model="modification_auth_form.path" placeholder="新菜单路径" prop="path" />
        </el-form-item>
        <el-form-item label="后端接口" prop="uri">
          <el-input v-model="oneAuth.uri" placeholder="接口" prop="uri" disabled />
        </el-form-item>
        <el-form-item label="新后端接口" prop="uri">
          <el-input v-model="modification_auth_form.uri" placeholder="新接口" prop="uri" />
        </el-form-item>
        <el-form-item label="是否隐藏" prop="isHidden">
          <el-switch v-model="oneAuth.isHidden" active-color="#13ce66" inactive-color="#ff4949" disabled />
        </el-form-item>
        <el-form-item label="修改隐藏状态" prop="new_isHidden">
          <el-switch v-model="modification_auth_form.isHidden" active-color="#13ce66" inactive-color="#ff4949" />
        </el-form-item>
        <el-form-item label="子菜单数" prop="countSub">
          <el-input v-model="oneAuth.countSub" placeholder="子菜单数" disabled />
        </el-form-item>
        <el-form-item label="新子菜单数" prop="new_countSub">
          <el-input v-model="modification_auth_form.countSub" placeholder="新子菜单数" />
        </el-form-item>
        <el-form-item label="组件名称" prop="component">
          <el-input v-model="oneAuth.component" placeholder="组件名称" disabled />
        </el-form-item>
        <el-form-item label="新组件名称" prop="component">
          <el-input v-model="modification_auth_form.component" placeholder="新组件名称" />
        </el-form-item>
        <el-form-item label="重定向" prop="redirect">
          <el-input v-model="oneAuth.redirect" placeholder="重定向路径" disabled />
        </el-form-item>
        <el-form-item label="新重定向" prop="redirect">
          <el-input v-model="modification_auth_form.redirect" placeholder="新重定向路径" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="oneAuth.sort" placeholder="排序" disabled />
        </el-form-item>
        <el-form-item label="新排序" prop="sort">
          <el-input v-model="modification_auth_form.sort" placeholder="新排序" />
        </el-form-item>
        <el-form-item label="超链接" prop="href">
          <el-input v-model="oneAuth.href" placeholder="超链接" disabled />
        </el-form-item>
        <el-form-item label="新超链接" prop="href">
          <el-input v-model="modification_auth_form.href" placeholder="新超链接" />
        </el-form-item>
        <el-form-item label="图标路径" prop="metaIcon">
          <el-input v-model="oneAuth.metaIcon" placeholder="图标" disabled />
        </el-form-item>
        <el-form-item label="新图标路径" prop="metaIcon">
          <el-input v-model="modification_auth_form.metaIcon" placeholder="新图标路径" />
        </el-form-item>
        <el-form-item label="模块名称" prop="module">
          <el-input v-model="oneAuth.module" placeholder="模块名称" disabled />
        </el-form-item>
        <el-form-item label="新模块名称" prop="new_module">
          <el-input v-model="modification_auth_form.module" placeholder="新模块名称" />
        </el-form-item>
        <el-form-item label="类型名称" prop="type">
          <el-input v-model="oneAuth.type" placeholder="类型名称" disabled />
        </el-form-item>
        <el-form-item label="新类型名称" prop="type">
          <el-input v-model="modification_auth_form.type" placeholder="新类型名称" />
        </el-form-item>
        <el-form-item label="允许" prop="permission">
          <el-input v-model="oneAuth.permission" placeholder="请确认数据的格式正确性" disabled />
        </el-form-item>
        <el-form-item label="新允许" prop="new_permission">
          <el-input v-model="modification_auth_form.permission" placeholder="请确认数据的格式正确性" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="modifyAction" :loading="loading" size="large">提交</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="cancelForm" size="large">返回</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

  </div>

</template>

<style scoped>
.auth_item {
  top: 30px;
  color: #69c4ff;
  margin-left: 20px;
  float: left;
  width: 300px;
  line-height: 100px;
}


.addAuthForm .el-form-item {
  margin-left: 50px;
}
</style>
